package com.soms.servlet;

import cn.hutool.json.JSONUtil;
import com.soms.constants.LoginConst;
import com.soms.entity.User;
import com.soms.service.UserService;
import com.soms.service.impl.UserServiceImpl;
import com.soms.util.DateUtil;
import com.soms.util.HttpResponseUtil;
import com.soms.util.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/server/auth")
public class AuthServlet extends HttpServlet {

    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        String type = req.getParameter("type");
        if (type != null) {
            switch (type) {
                case "loginInfo":
                    getLoginInfo(req, resp);
                    break;
                case "logout":
                    doLogout(req, resp);
                    break;
                default:

                    break;
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req,
                          HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 获取当前登录的用户信息
     */
    private void getLoginInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession(false);
        // 如果之前还没有会话，或会话中没有存储用户信息，则认为没有登录
        if (session == null || session.getAttribute(LoginConst.USER_CODE) == null) {
            HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.unAuthenticated()));
            return;
        }
        String userCode = (String)session.getAttribute(LoginConst.USER_CODE);
        User user = userService.getUserByUserCode(userCode);
        if (user == null) {
            // 用户登录了，但是这个账号被其他人删掉了
            session.invalidate();
            HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.unAuthenticated()));
        } else {
            Map<String, Object> data = new HashMap<>();
            data.put("loginUser", user);
            data.put("loginTime", DateUtil.getDateTimeString(session.getCreationTime()));
            data.put("timeout", session.getMaxInactiveInterval());
            HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.success(null, data)));
        }
    }

    /**
     * 退出登录，本质是销毁session中的userCode数据，或直接销毁会话本身
     *
     * @param req
     * @param resp
     */
    private void doLogout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute(LoginConst.USER_CODE) != null) {
            // 登录的这种情况，销毁会话
            session.invalidate();
        }
        HttpResponseUtil.writeJson(resp, JSONUtil.toJsonStr(ResultUtil.success()));
    }
}
